import React, {Component} from 'react';
import * as URLconstant from '../constant/URLconstant';
import Util from '../common/util';
import ViewShot, {captureRef, captureScreen} from "react-native-view-shot";
import {
    View,
    Text,
    Image,
    StyleSheet,
    Dimensions,
    TouchableOpacity,
    ScrollView,
    Slider,
    PanResponder, Platform, CameraRoll, NativeModules,
    ImageBackground,
    Alert
} from 'react-native'


export default class scene extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loaded: false,
            loadedImg: false,
            loadedFrame: false,
            selectCate: null,
            slideValue: 0.5,
            maxWidth: Util.size.width / 2,
            minWidth: 50,
            imgList: [],
            showType: 1,//1:场景 2:收藏
            collectList: [],
            isOpen: false
        };
    }

    componentDidMount() {
        this._panResponder = PanResponder.create({
            onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder.bind(this),
            onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder.bind(this),
            onPanResponderGrant: this._handlePanResponderGrant.bind(this),
            onPanResponderMove: this._handlePanResponderMove.bind(this),
            onPanResponderRelease: this._handlePanResponderEnd.bind(this),
            onPanResponderTerminate: this._handlePanResponderEnd.bind(this),
            onPanResponderStart: this._onPanResponderStart.bind(this)
        });
        this.getCollect()
        let url = URLconstant.GET_SCENE
        let datakey = []
        Util.get(url, datakey, (datas) => {
            if (datas.status == 0) {
                let sceneCate = datas.data.scene
                let sceneList = datas.data.scene_list
                this.setState({
                    selectCate: sceneCate[0],
                    sceneCate: sceneCate,
                    selectScene: sceneList[0],
                    sceneList: sceneList,
                    loaded: true
                })
                this.getImageInfo(sceneList[0].image_url)
            }
        }, (err) => {

        })
    }

    getCollect() {
        let url = URLconstant.GET_COLLECT
        let user_id = '123456'
        let datakey = []
        datakey['user_id'] = user_id
        Util.get(url, datakey, (datas) => {
            if (datas.status == 0) {
                this.setState({
                    collectList: datas.data
                })
            }
        }, (err) => {

        })
    }


    _handleStartShouldSetPanResponder() {
        return true
    }

    _handleMoveShouldSetPanResponder() {
        // return true
    }

    _handlePanResponderGrant(e, gestureState) {

    }

    _handlePanResponderMove(e, gestureState) {
        let imgList = this.state.imgList
        for (let item of imgList) {
            if (item.active) {
                let imgWidth = item.width
                let imgHeight = item.height
                let frameWidth = this.state.frameWidth
                let frameHeight = this.state.frameHeight
                let move_x = gestureState.dx
                let move_y = gestureState.dy
                let top = item.topInit
                let left = item.leftInit
                top = top + move_y
                left = left + move_x
                if (top < 0) {
                    top = 0
                }
                if (top > imgHeight - frameHeight) {
                    top = imgHeight - frameHeight
                }
                if (left < 0) {
                    left = 0
                }
                if (left > imgWidth - frameWidth) {
                    left = imgWidth - frameWidth
                }
                item.top = top
                item.left = left
            }
        }
        this.setState({
            imgList: imgList
        })
    }

    _handlePanResponderEnd(e, gestureState) {
        let imgList = this.state.imgList
        for (let item of imgList) {
            if (item.active) {
                item.topInit = item.top
                item.leftInit = item.left
            }
        }
        this.setState({
            imgList: imgList
        })
    }

    _onPanResponderStart(e, gestureState) {
        let x = gestureState.x0
        let y = gestureState.y0
        LOG('x===' + x, 'y===' + y)
        let imgList = this.state.imgList
        for (let item of imgList) {
            item.active = false
        }
        for (let item of imgList) {
            let point_1 = item.left //左
            let point_2 = item.left + item.width //右
            let point_3 = item.top //上
            let point_4 = item.top + item.height //下
            LOG('横判读', 'x===' + x, 'left1==' + point_1, 'left2==' + point_2)
            LOG('竖判断', 'y===' + y, 'top1===' + point_3, 'top2===' + point_4)
            if (x >= point_1 && x <= point_2 && y >= point_3 && y <= point_4) {
                item.active = true
                break;
            } else {

            }
        }
        LOG('imgList====' + JSON.stringify(imgList))
        this.setState({
            imgList: imgList
        })
    }

    getScene() {
        let url = URLconstant.GET_SCENE_GOODS
        let datakey = []
        let selectCate = this.state.selectCate
        datakey['item_type'] = selectCate.item_type
        Util.get(url, datakey, (datas) => {
            if (datas.status == 0) {
                let sceneList = datas.data.goods
                if(sceneList&&sceneList.length>0){
                    this.setState({
                        sceneList: sceneList,
                        selectScene: sceneList[0],
                    })
                    this.getImageInfo(sceneList[0].image_url)
                }else{
                    this.setState({
                        loadedImg: true
                    })
                    Alert.alert('当前分类下没有可以预览的场景')
                }

            }
        },(err)=>{
            LOG('err===='+err)
        })
    }


    getFrame() {
        let {frameImg} = this.props.route.params
        let frame = frameImg
        Image.getSize(frame, (width, height) => {
            let slideValue = this.state.slideValue
            let maxWidth = this.state.maxWidth
            let minWidth = this.state.minWidth
            let frameWidth = maxWidth * slideValue + minWidth
            let frameHeight = frameWidth * height / width;
            let imgWidth = this.state.imgWidth
            let imgHeight = this.state.imgHeight
            let left = (imgWidth - frameWidth) / 2
            let top = (imgHeight - frameHeight) / 2
            let obj = {
                width: frameWidth,
                height: frameHeight,
                uri: frame,
                left: left,
                top: top,
                leftInit: left,
                topInit: top,
                active: true,
                index: 1
            }
            let imgList = []
            imgList.push(obj)
            this.setState({
                imgList: imgList,
                loadedFrame: true
            })
        })
    }


    getImageInfo(url) {
        Image.getSize(url, (width, height) => {
            let imgWidth = Util.size.width
            let imgHeight = imgWidth * height / width;
            this.setState({
                imgWidth: imgWidth,
                imgHeight: imgHeight,
                loadedImg: true
            })
            this.getFrame()
        }, (error) => {
            LOG('图片路径错误。。。。。。。。' + error);
        })
    }

    //选择场景分类
    async selectCate(item) {
        await this.setState({
            selectCate: item,
            loadedImg: false,
            loadedFrame: false,
        })
        this.getScene()
    }

    //选择场景
    async selectScene(item) {
        await this.setState({
            selectScene: item,
            loadedImg: false,
            loadedFrame: false
        })
        this.getImageInfo(item.image_url)
    }


    async changeValue(value) {
        LOG('value==' + value)
        this.setState({
            slideValue: value
        })
        let imgList = this.state.imgList
        for (let item of imgList) {
            if (item.active) {
                let maxWidth = this.state.maxWidth
                let minWidth = this.state.minWidth
                let width = maxWidth * value + minWidth
                let frameWidth = item.width
                let frameHeight = item.height
                let height = frameHeight / (frameWidth / width)
                let left = item.left
                let top = item.top
                left = left + (frameWidth - width) / 2
                top = top + (frameHeight - height) / 2
                item.width = width
                item.height = height
                item.left = left
                item.top = top
                item.leftInit = left
                item.topInit = top
            }
        }
        this.setState({
            imgList: imgList
        })
    }


    //选择显示收藏的画框
    selectCollect(uri) {
        let imgList = this.state.imgList
        if (imgList.length >= 5) {
            Toast.show('最多显示5张')
            return false
        }
        for (let item of imgList) {
            item.active = false
        }

        Image.getSize(uri, (width, height) => {
            let slideValue = this.state.slideValue
            let maxWidth = this.state.maxWidth
            let minWidth = this.state.minWidth
            let frameWidth = maxWidth * slideValue + minWidth
            let frameHeight = frameWidth * height / width;
            let imgWidth = this.state.imgWidth
            let imgHeight = this.state.imgHeight
            let left = (imgWidth - frameWidth) / 2
            let top = (imgHeight - frameHeight) / 2
            let obj = {
                width: frameWidth,
                height: frameHeight,
                uri: uri,
                left: left,
                top: top,
                leftInit: left,
                topInit: top,
                active: true,
                index: imgList.length + 1
            }
            imgList.push(obj)
            this.setState({
                imgList: imgList,
            })
        })
    }

    showControlView() {
        let selectCate = this.state.selectCate
        let selectScene = this.state.selectScene
        let sceneCate = this.state.sceneCate
        let sceneList = this.state.sceneList
        let showType = this.state.showType
        let collectList = this.state.collectList
        return (
            <View>
                <View style={{paddingHorizontal: 10, paddingVertical: 15, flexDirection: "row", alignItems: 'center'}}>
                    <Text style={{fontSize: 12, color: "#969696"}}>滑动按钮控制元素大小</Text>
                    <Slider
                        style={{flex: 1, height: 20}}
                        value={this.state.slideValue}
                        onValueChange={(value) => {
                            this.changeValue(value)
                        }}
                    />
                </View>
                <View style={{
                    alignItems: 'center',
                    justifyContent: 'center',
                    paddingVertical: 15,
                    borderBottomWidth: 1,
                    borderBottomColor: "#e0e0e0"
                }}>
                    <View style={styles.btn_radio_view}>
                        <TouchableOpacity
                            onPress={() => this.setState({showType: 1})}
                            style={showType == 1 ? styles.select_view : styles.normal_view}>
                            <Text>场景</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => this.setState({showType: 2})}
                            style={showType == 2 ? styles.select_view : styles.normal_view}>
                            <Text>收藏</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                {
                    showType == 1 ?
                        <View style={{paddingTop: 10}}>
                            <ScrollView horizontal={true} style={{backgroundColor: "#f2f2f2", paddingHorizontal: 15}}>
                                {
                                    sceneCate.map((item, index) => {
                                        return (
                                            <TouchableOpacity
                                                onPress={() => this.selectCate(item)}
                                                style={[styles.normal_item, item.id == selectCate.id ? styles.select_item : null]}
                                                key={index}>
                                                <Text
                                                    style={item.id == selectCate.id ? {fontSize: 14, color: "#f00"} : {
                                                        fontSize: 14,
                                                        color: "#333"
                                                    }}>{item.item_type_str}</Text>
                                            </TouchableOpacity>
                                        )
                                    })
                                }
                            </ScrollView>
                            <ScrollView horizontal={true}
                                        style={{paddingTop: 15, paddingBottom: 10, paddingHorizontal: 15}}>
                                {
                                    sceneList.map((item, index) => {
                                        return (
                                            <TouchableOpacity
                                                onPress={() => this.selectScene(item)}
                                                style={[styles.normal_scene, item.id == selectScene.id ? styles.select_scene : null]}
                                                key={index}>
                                                <Image
                                                    source={{uri: item.image_url}}
                                                    resizeMode={'cover'}
                                                    style={{width: 60, height: 60, marginBottom: 5}}
                                                />
                                                <Text style={{fontSize: 12, color: "#696969"}}>{item.title}</Text>
                                            </TouchableOpacity>
                                        )
                                    })
                                }
                            </ScrollView>
                        </View> :
                        <ScrollView horizontal={true}
                                    style={{paddingTop: 15, paddingBottom: 10, paddingHorizontal: 15}}>
                            {
                                collectList.map((item, index) => {
                                    return (
                                        <TouchableOpacity
                                            onPress={() => this.selectCollect(item.images)}
                                            key={index} style={[styles.normal_scene, {width: 70}]}>
                                            <Image
                                                source={{uri: item.images}}
                                                resizeMode={'contain'}
                                                style={{width: 70, height: 70, marginBottom: 5}}
                                            />
                                            <Text style={{
                                                fontSize: 12,
                                                color: "#696969",
                                                textAlign: 'center'
                                            }}>{item.add_time}</Text>
                                        </TouchableOpacity>
                                    )
                                })
                            }
                        </ScrollView>
                }

            </View>
        )
    }

    showFrameView() {
        let imgList = this.state.imgList
        let list = []
        let rows
        for (let item of imgList) {
            rows = (
                <View
                    key={item.index}
                    style={[
                        {
                            width: item.width, height: item.height,
                            position: 'absolute', top: item.top, left: item.left,
                        },
                        item.active ? {zIndex: 9999} : {zIndex: 9}
                    ]}
                >
                    <ImageBackground
                        source={{uri: item.uri}}
                        resizeMode={'cover'}
                        style={{
                            width: item.width,
                            height: item.height,
                        }}
                    >
                        {
                            item.active == true ?
                                <TouchableOpacity
                                    onPress={() => this.onPressClose()}
                                    style={{
                                        width: 25,
                                        height: 25,
                                        position: 'absolute',
                                        top: 0,
                                        right: 0,
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                    }}
                                >
                                    <Image
                                        source={require('../imgs/close_btn.png')}
                                        resizeMode={'cover'}
                                        style={{width: 20, height: 20}}
                                    />
                                </TouchableOpacity> : null
                        }
                    </ImageBackground>
                </View>
            )
            list.push(rows)
        }
        return list
    }

    onPressClose() {
        let imgList = this.state.imgList
        let length = imgList.length
        if (length == 1) {
            Alert.alert('已经是最后一幅')
            return false
        }
        for (let i = 0; i < length; i++) {
            if (imgList[i].active == true) {
                imgList.splice(i, 1)
            }
        }
        length = imgList.length
        imgList[length - 1].active = true
        this.setState({
            imgList: imgList
        })
    }

    _pop() {
        this.props.navigation.pop()
    }

    showHeader() {
        return (
            <View style={styles.header}>
                <TouchableOpacity style={styles.header_back} onPress={() => this._pop()}>
                    <Image
                        source={require('../imgs/jy_02.png')}
                        resizeMode={'cover'}
                        style={{width: 17, height: 17, marginBottom: 2}}
                    />
                </TouchableOpacity>
                <Text style={{fontSize: 16, color: "#000"}}>场景预览</Text>
                <View style={styles.opera_view}>
                    <TouchableOpacity
                        onPress={() => this.setState({isOpen: true})}
                        style={styles.header_back2}>
                        <Image
                            source={require('../imgs/match_04.jpg')}
                            resizeMode={'cover'}
                            style={{width: 17, height: 17, marginBottom: 2}}
                        />
                        <Text style={{fontSize: 12, color: "#333"}}>分享</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    saveImage() {
        captureRef(this.refs['shotView'])
            .then(res =>
                this.saveImageToAlbum(res)
            )
            .catch(
                error => (
                    Toast.show(error)
                )
            );
    }

    backName(res) {
        return list = res.split('/').pop()
    }

    saveImageToAlbum(uri) {
        let url = URLconstant.UPLOAD_IMAGE
        let datakey = []
        let upload_photo = {
            uri: uri,
            type: "multipart/form-data",
            name: this.backName(uri)
        }
        datakey['image_file_link'] = upload_photo
        let that = this
        that.setState({
            isOpen: false
        })
        Util.post(url, datakey, (datas) => {
            if (datas.status == 0) {
                let img = datas.data
                if (Platform.OS === 'android') {
                    //LOG("保存图片成功 data==" + uri);
                    SaveModule.initSave(img, (obj) => {
                        Toast.show("保存图片成功");
                    }, (err) => {
                        Toast.show("保存图片失败");
                    });
                } else {
                    CameraRoll.saveImageWithTag(img).done(function (data) {
                        LOG("保存图片成功 data==" + data);
                        Toast.show("保存图片成功", 2);
                    }, function (err) {
                        LOG("保存图片失败 err==" + err);
                        Toast.show("保存图片失败", 2);

                    });
                }
            } else {
                Toast.show(datas.msg)
            }
        }, (err) => {
            LOG('err===='+err)
        })
    }


    render() {
        return (
            <View style={{flex: 1,backgroundColor:"#fff"}}>
                {this.showHeader()}
                {
                    !this.state.loaded ?
                        <View style={{flex: 1}}>
                            {Util.loading()}
                        </View> :
                        <View style={{flex: 1}}>
                            {
                                !this.state.loadedImg ?
                                    <View style={{flex: 1}}>
                                        {Util.loading()}
                                    </View> :
                                    <ScrollView style={{flex: 1}}>
                                        <View>
                                            <ViewShot
                                                ref="shotView"
                                            >
                                                <View
                                                    {...this._panResponder.panHandlers}
                                                >
                                                    <ImageBackground
                                                        source={{uri: this.state.selectScene.image_url}}
                                                        resizeMode={'cover'}
                                                        style={{
                                                            width: this.state.imgWidth,
                                                            height: this.state.imgHeight,
                                                            overflow:'hidden'
                                                        }}
                                                    >
                                                        {this.showFrameView()}
                                                    </ImageBackground>
                                                </View>
                                            </ViewShot>
                                        </View>

                                    </ScrollView>
                            }
                            {this.showControlView()}
                        </View>
                }
            </View>
        )
    }
}
var styles = StyleSheet.create({
    header: {
        width: Util.size.width,
        height: 50,
        justifyContent: 'space-between',
        alignItems: "center",
        flexDirection: 'row',
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#e0e0e0"
    },
    header_back: {
        width: 50,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'column'
    },
    header_back2: {
        paddingLeft: 10,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'column'
    },
    normal_item: {
        paddingHorizontal: 15,
        height: 35,
        justifyContent: 'center',
        alignItems: 'center',
        borderBottomWidth: 2,
        borderBottomColor: 'transparent',
        marginHorizontal: 10
    },
    select_item: {
        borderBottomColor: '#f00'
    },
    normal_scene: {
        padding: 5,
        alignItems: 'center',
        justifyContent: 'center',
        marginHorizontal: 5
    },
    select_scene: {
        backgroundColor: "#f2f2f2"
    },
    close_btn_view: {
        position: 'absolute',
        top: -7,
        right: -7,
        width: 18,
        height: 18,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 9,
        borderWidth: 1,
        borderColor: "#f00",
        backgroundColor: "#fff"
    },
    btn_radio_view: {
        borderRadius: 5,
        width: 100,
        height: 30,
        backgroundColor: "#d7d7d7",
        flexDirection: "row",
        padding: 1
    },
    normal_view: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    },
    select_view: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: "#fff",
        borderRadius: 5
    },
    opera_view: {
        flexDirection: 'row',
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        paddingRight: 10
    },
    save_modal: {
        width: Util.size.width,
        height: 101,
        backgroundColor: 'transparent'
    }
})